package com.cndw.kungfu.model.goods;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.goods.domain.Discount;

public class DiscountCenter {

	
	public static int refreshTime = 0;
	
	public static final int IntervalTime = 4 * 3600;
	
	public static Set<Integer> ids;
	
	public static ConcurrentHashMap<Integer, ConcurrentHashMap<Long,Boolean>> buyLogs = new ConcurrentHashMap<Integer, ConcurrentHashMap<Long,Boolean>>();
	
	public static Set<Integer> getIds(){
		refresh();

		return ids;
	}
	
	
	public static synchronized void refresh(){
		if (ids == null || refreshTime + IntervalTime <= TimeProcesser.getUnixTime()) {
			Collection<Discount> discounts = Discount.getAll();
			ArrayList<Discount> list = new ArrayList<Discount>(discounts);
			Collections.shuffle(list);
			int i = 0;
			Set<Integer> tmpIds = new HashSet<Integer>();
			for (Discount discount : list) {
				if (discount.getDays() > 0 && TimeProcesser.dayInterval(ConstantsConfig.getSysCgOpenTime()) < discount.getDays()) {
					continue;
				}
				tmpIds.add(discount.getId());
				i++;
				if (i >= 5) {
					break;
				}
			}
			ids = tmpIds;
			buyLogs.clear();
			int morningTime = TimeProcesser.getMorningTime();
			int diff =( TimeProcesser.getUnixTime() - morningTime)/IntervalTime;
			refreshTime = morningTime + diff * IntervalTime;
		}
		
	}
	public static void buyRecord(long uid,int id){
		if (!buyLogs.containsKey(uid)) {
			buyLogs.putIfAbsent(id, new ConcurrentHashMap<Long, Boolean>());
		}
		buyLogs.get(id).put(uid, true);
	}
	public static boolean canBuy(long uid,int id){
		return ids.contains(id) && (!buyLogs.containsKey(id) || !buyLogs.get(id).containsKey(uid));
	}
	public static int getHaveNum(int id){
		return buyLogs.containsKey(id) ? buyLogs.get(id).size() : 0;
	}


	public static int getNextRefreshTime() {
		return refreshTime + IntervalTime;
	}
	
	
}
